package com.lemon.boot.common.utils;

import cn.hutool.core.lang.Dict;
import com.lemon.boot.common.web.Result;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author 李猛
 * @datetime 2024/6/11 19:28
 * @description 检测对象中的属性是否为空
 */
@Slf4j
public final class ObjectFieldUtil {
    /**
     * 判断对象里的属性是否为空
     *
     * @param source
     * @param fields
     * @return
     */
    public static <T> Result<String> isNull(T source, String... fields) {
        //1.初始化返回结果
        if (Objects.isNull(source)) {
            return Result.fail("数据为空！");
        }

        //2.获取对象中的所有属性
        Field[] declaredFields = source.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //3.设置字段是否可访问
            boolean accessible = declaredField.isAccessible();
            if (!accessible) {
                declaredField.setAccessible(true);
            }

            //4.获取属性名
            String name = declaredField.getName();

            //5.判断是否要检查
            if (Arrays.asList(fields).contains(name)) {
                //6.获取字段的值
                Object value = null;
                try {
                    value = declaredField.get(source);
                } catch (IllegalAccessException e) {
                    log.error("CheckObjectFieldUtil.isNull.message:{}", e.getMessage());
                }

                //7.判断值是否为空
                if (Objects.isNull(value)) {
                    //8.获取属性上的注解 @ApiModelProperty
                    ApiModelProperty property = declaredField.getAnnotation(ApiModelProperty.class);
                    return Result.fail(String.format("\"%s\"为空！", property == null ? name : property.value()));
                }
            }

        }

        //返回结果
        return Result.ok();
    }

    /**
     * 给实体类属性设置为null
     *
     * @param source
     * @param fields
     * @param <T>
     * @return
     */
    public static <T> T setNull(T source, String... fields) {
        //1.获取所有属性
        Field[] declaredFields = source.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            //2.设置字段是否可访问
            boolean accessible = declaredField.isAccessible();
            if (!accessible) {
                declaredField.setAccessible(true);
            }

            //3.获取属性名
            String name = declaredField.getName();

            //4.判断是否要设置为null
            if (Arrays.asList(fields).contains(name)) {
                try {
                    declaredField.set(source, null);
                } catch (IllegalAccessException e) {
                    log.error("CheckObjectFieldUtil.setNull.message:{}", e.getMessage());
                }
            }
        }

        return source;
    }
}
